<template>
  <div class="vab-form-table">
    <vab-query-form>
      <vab-query-form-top-panel :span="12">
        <el-button type="primary" @click="handleAdd($event)">添加</el-button>
      </vab-query-form-top-panel>
    </vab-query-form>
    <el-table :key="toggleIndex" ref="tableRef" border :data="data">
      <el-table-column v-if="drag" align="center" label="操作" width="120">
        <template slot="default">
          <vab-icon
            class="vab-rank"
            icon="drag-move-2-line"
            style="cursor: move"
          />
        </template>
      </el-table-column>

      <slot></slot>
      <el-table-column align="center" label="操作" width="120">
        <template slot-scope="scope">
          <el-button
            plain
            type="danger"
            @click="handleDelete(scope.row, scope.$index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
      <template slot="empty">
        <el-empty class="vab-data-empty" description="暂无数据" />
      </template>
    </el-table>
  </div>
</template>

<script>
  // import { Delete, Plus } from '@element-ui/icons-vue'
  import Sortable from 'sortablejs'

  export default {
    name: 'VabFormTable',
    props: {
      value: {
        type: Array,
        default: () => [],
      },
      rowTemplate: {
        type: Object,
        default: () => {},
      },
      drag: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        tableRef: null,
        data: [],
        toggleIndex: 0,
      }
    },
    watch: {
      value() {
        console.log('value', this.value)
        this.data = this.value
      },
      data() {
        this.$emit('input', this.data)
      },
    },
    mounted() {
      this.data = this.value
      if (this.drag) this.rowDrop()
    },
    methods: {
      rowDrop() {
        const tbody = this.$refs.tableRef.$el.querySelector(
          '.el-table__body-wrapper tbody'
        )
        Sortable.create(tbody, {
          handle: '.vab-rank',
          animation: 300,
          onEnd({ newIndex, oldIndex }) {
            const tableData = this.data
            const currRow = tableData.splice(oldIndex, 1)[0]
            tableData.splice(newIndex, 0, currRow)
            this.toggleIndex += 1
            nextTick(() => {
              this.rowDrop()
            })
          },
        })
      },
      handleAdd(e) {
        console.log('handleAdd', e)
        this.data.push(JSON.parse(JSON.stringify(this.rowTemplate)))
      },
      handleDelete(row, index) {
        this.data.splice(index, 1)
      },
    },
  }
</script>
